package org.wxd.media.schdcenter;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wxd.common.utils.Base64;
import org.wxd.media.api.MediaQueryService;
import org.wxd.media.api.MediaService;
import org.wxd.media.api.record.MediaDownLoadResult;
import org.wxd.media.api.record.MediaRecord;
import org.wxd.media.api.record.MediaUploadRequest;
import org.wxd.media.schdcenter.base.SchdcenterHandler;
import org.wxd.media.schdcenter.config.MqConfig;

/**
 * Created by wangxd on 2016/11/5.
 */
@Component
public class MediaSchdcenter extends SchdcenterHandler {
    @Autowired
    MediaQueryService queryService;
    @Autowired
    MediaService service;

    @RabbitHandler
    @RabbitListener(queues = MqConfig.Queue.MediaCenter.UP_LOAD)
    public Message upload(Message message) {
        MediaUploadRequest request = getMessage(message, MediaUploadRequest.class);
        MediaRecord record = service.upload(request);
        return buildMessage(record);
    }

    @RabbitHandler
    @RabbitListener(queues = MqConfig.Queue.MediaCenter.DOWN_LOAD)
    public Message download(Message message) {
        String mediaId = getMessage(message, String.class);
        MediaDownLoadResult.Builder builder = MediaDownLoadResult.newBuilder();
        queryService.downLoad(
                mediaId,
                (name, type, body, metaData) -> builder.name(name).contentType(type).body(Base64.enToString(body)).metaData(metaData).mediaId(mediaId)
        );
        return buildMessage(builder.build());
    }

}
